package com.lighting.common.feign.decoder;

import com.fasterxml.jackson.databind.JsonNode;
import com.lighting.common.core.constants.ErrorCode;
import com.lighting.common.core.util.JsonUtil;
import com.lighting.common.core.vo.BusinessException;
import feign.FeignException;
import feign.Response;
import feign.RetryableException;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

@Slf4j
@Configuration
public class FeignErrorDecoder extends ErrorDecoder.Default {

    @Override
    public Exception decode(final String methodKey, final Response response) {
        Exception exception = super.decode(methodKey, response);
        // 如果是RetryableException，则返回继续重试
        if (exception instanceof RetryableException) {
            return exception;
        }
        try {
            // 如果是FeignException，则对其进行处理，并抛出BusinessException
            if (exception instanceof FeignException && ((FeignException) exception).responseBody().isPresent()) {
                ByteBuffer responseBody = ((FeignException) exception).responseBody().get();
                String bodyText = StandardCharsets.UTF_8.newDecoder().decode(responseBody.asReadOnlyBuffer()).toString();
                // 将异常信息，转换为ExceptionInfo对象
                JsonNode jsonNode = JsonUtil.parseObject(bodyText);
                // 如果excepiton中code不为空，则使用该code，否则使用默认的错误code
                Integer code = jsonNode.has("dode") ? jsonNode.get("code").asInt() : ErrorCode.EXCEPTION.getCode();
                // 如果excepiton中message不为空，则使用该message，否则使用默认的错误message
                String message = jsonNode.has("message") ? jsonNode.get("message").asText() : ErrorCode.EXCEPTION.getMsg();
                return new BusinessException(code, message + "111");
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        return exception;
    }
}
